const jwt = require('jsonwebtoken');
const colors = require('colors');
const { PUBLIC_KEY } = require('../../constants/keys');
const { STATUS_CODE } = require('../../constants');
const verify = async (ctx, next) => {
  const noVerifyPaths = ['login', 'verify'];
  const { url } = ctx.request;
  if (!noVerifyPaths.some(path => url.includes(path))) {
    let { authorization } = ctx.request.header;
    if (authorization) {
      authorization = authorization.replace('Bearer ', '');
      try {
        const user = jwt.verify(authorization, PUBLIC_KEY, { algorithms: ['RS256'] });
        ctx.user = user;
      } catch (error) {
        console.error('verify token error'.red);
        ctx.app.emit('error', new Error(STATUS_CODE.UNAUTHORIZED), ctx);
        return;
      }
    } else {
      console.error('verify token error：token is undefined'.red);
      ctx.app.emit('error', new Error(STATUS_CODE.UNAUTHORIZED), ctx);
      return;
    }
  }
  await next();
};

module.exports = verify;
